<template>
  <div class="contract-upload">
    <div class="page-header">
      <h1 class="title">合同审查，一键开启审查</h1>
      <p class="subtitle">快速识别合同潜在风险，提供专业的风险评估和修改建议</p>
    </div>

    <!-- 历史记录按钮 -->
    <div class="history-button" @click="showHistory">
      <i class="el-icon-time"></i> 历史记录
    </div>

    <div class="upload-container">
      <!-- 文件上传进度显示 -->
      <div v-if="uploadProgress.visible" class="upload-progress-overlay">
        <div class="upload-progress-container">
          <i class="el-icon-document"></i>
          <div class="progress-text">文件解析中，进度{{ uploadProgress.percent }}%...</div>
          <el-progress :percentage="uploadProgress.percent" :show-text="false"></el-progress>
        </div>
      </div>

      <el-upload
        class="upload-area"
        drag
        :action="uploadUrl"
        :headers="uploadHeaders"
        name="upfile"
        :before-upload="beforeUpload"
        :on-success="handleSuccess"
        :on-error="handleError"
        :multiple="false"
        :show-file-list="false"
        accept=".pdf,.doc,.docx"
      >
        <div class="upload-content">
          <i class="el-icon-upload"></i>
          <div class="upload-text">点击或将文档拖拽到这里上传</div>
          <div class="upload-hint">单个合同文件的字数不超过10万字，格式支持：pdf/doc/docx</div>
        </div>
      </el-upload>

      <div class="upload-info" v-if="fileInfo">
        <div class="file-name">{{ fileInfo.name }}</div>
        <div class="file-size">{{ formatFileSize(fileInfo.size) }}</div>
        <el-button type="text" @click="removeFile">删除</el-button>
      </div>
    </div>

    <!-- 历史记录弹窗 -->
    <el-dialog title="历史记录" :visible.sync="historyDialogVisible" width="800px">
      <div class="history-dialog-content">
        <div class="history-search">
          <el-input
            placeholder="请输入文件名进行搜索"
            v-model="historySearchKeyword"
            prefix-icon="el-icon-search"
            clearable
            @keyup.enter.native="searchHistory"
            @clear="resetSearch">
            <el-button slot="append" icon="el-icon-search" @click="searchHistory">搜索</el-button>
          </el-input>
        </div>
        <div class="history-tabs">
          <el-tabs v-model="activeHistoryTab">
            <el-tab-pane label="历史" name="history"></el-tab-pane>
          </el-tabs>
        </div>
        <div class="history-list" v-loading="historyLoading">
          <div
            v-for="(item, index) in historyList"
            :key="index"
            class="history-item">
            <div class="history-item-content" @click="selectHistoryItem(item)">
              <div class="history-item-name">{{ item.fileName }}</div>
              <div class="history-item-info">
                <span class="history-item-date" v-if="item.createTime">创建时间: {{ formatDate(item.createTime) }}</span>
                <span class="history-item-status" :class="getStatusClass(item.reviewStatus)">
                  {{ getStatusText(item.reviewStatus) }}
                </span>
              </div>
            </div>
            <div class="history-item-actions">
              <el-button type="danger" size="mini" icon="el-icon-delete" @click.stop="deleteHistoryItem(item)">删除</el-button>
            </div>
          </div>
          <div v-if="historyList.length === 0" class="empty-history">
            <i class="el-icon-document"></i>
            <p>{{ historySearchKeyword ? '没有找到匹配的文件记录' : '暂无历史记录' }}</p>
          </div>
        </div>
        <!-- 分页器 -->
        <div class="pagination-container">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pagination.current"
            :page-sizes="[10, 20, 50]"
            :page-size="pagination.size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pagination.total">
          </el-pagination>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {Store} from "vuex";
import axios from 'axios';
import { contractList, pageContract, cascadeDeleteContract } from "@/api/contract";

export default {
  name: 'ContractUpload',
  data() {
    return {
      uploadUrl: window.$conf.commonConf.baseUrl + "/system/oss/upload",
      fileInfo: null,
      quota: 3, // 默认剩余额度
      uploadHeaders: {
        Authorization: 'Bearer ' + (localStorage.getItem("token") || Store.state.token)
      },
      uploadProgress: {
        visible: false,
        percent: 0
      },
      progressTimer: null,  // 用于存储进度条定时器

      // 历史记录相关
      historyDialogVisible: false,
      historyList: [],
      historySearchKeyword: '',
      activeHistoryTab: 'history',
      pagination: {
        current: 1,
        size: 20,
        total: 0
      },
      historyLoading: false
    }
  },
  computed: {
    // 不再需要filteredHistoryList，直接使用historyList
  },
  created() {

  },
  methods: {
    // 显示历史记录弹窗
    showHistory() {
      this.historyDialogVisible = true;
      this.pagination.current = 1;
      this.pagination.size = 20;
      this.historySearchKeyword = '';
      this.getHistoryList();
    },

    // 搜索历史记录
    searchHistory() {
      this.pagination.current = 1;
      this.getHistoryList();
    },

    // 重置搜索
    resetSearch() {
      this.historySearchKeyword = '';
      this.pagination.current = 1;
      this.getHistoryList();
    },

    // 处理每页显示条数变化
    handleSizeChange(val) {
      this.pagination.size = val;
      this.getHistoryList();
    },

    // 处理页码变化
    handleCurrentChange(val) {
      this.pagination.current = val;
      this.getHistoryList();
    },

    // 获取历史记录列表
    async getHistoryList() {
      try {
        // 显示加载状态
        this.$set(this, 'historyLoading', true);

        // 准备查询参数对象，包含搜索关键词
        const queryParams = {};
        if (this.historySearchKeyword && this.historySearchKeyword.trim() !== '') {
          queryParams.fileName = this.historySearchKeyword.trim();
        }

        // 使用新的pageContract API
        const response = await pageContract(
          queryParams,
          this.pagination.current,
          this.pagination.size
        );

        if (response && response.code === 0 && response.data) {
          this.historyList = response.data.records || [];
          this.pagination.total = response.data.total || 0;
          console.log('获取到历史记录:', this.historyList);
        } else {
          console.warn('获取历史记录失败:', response);
          this.$message.warning('获取历史记录失败');

          // 尝试使用旧的contractList API作为备选
          this.getHistoryListFallback();
        }
      } catch (error) {
        console.error('获取历史记录出错:', error);
        this.$message.error('获取历史记录出错');
      } finally {
        // 无论成功还是失败，都关闭加载状态
        this.$set(this, 'historyLoading', false);
      }
    },


    // 选择历史记录项
    selectHistoryItem(item) {
      this.historyDialogVisible = false;

      // 导航到合同审查页面
      this.$router.push({
        path: '/home/contract/review',
        query: {
          contractId: item.id || item.contractId, // 确保传递contractId
          fileId: item.id || item.contractId,
          fileName: item.fileName || '',
          fileUrl: item.fileUrl || '',
          fileSize: item.fileSize || 0,
          contractType: item.contractType || '',
          contractAmount: item.contractAmount || '',
          contractTerm: item.contractTerm || '',
          contentSummary: item.contentSummary || '',
          partyA: item.partyA || '',
          partyB: item.partyB || '',
          // 确保currentStep是数字，默认为0
          currentStep: parseInt(item.currentStep || '0', 10)
        }
      });
    },

    beforeUpload(file) {
      const isValidType = ['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'].includes(file.type)
      if (!isValidType) {
        this.$message.error('请上传PDF或Word格式的文件')
        return false
      }

      const maxSize = 10 * 1024 * 1024 // 10MB
      if (file.size > maxSize) {
        this.$message.error('文件大小不能超过10MB')
        return false
      }

      // 显示进度条并启动模拟进度
      this.uploadProgress.visible = true;
      this.uploadProgress.percent = 0;
      this.startFakeProgress();

      return true
    },

    // 开始模拟进度
    startFakeProgress() {
      // 清除可能存在的定时器
      if (this.progressTimer) {
        clearInterval(this.progressTimer);
      }

      // 启动新的定时器，模拟上传进度
      this.progressTimer = setInterval(() => {
        // 如果当前进度小于90%，继续增加
        if (this.uploadProgress.percent < 90) {
          // 随机增加进度，但速度逐渐变慢
          const increment = Math.max(1, 10 * Math.random() * (1 - this.uploadProgress.percent / 100));
          this.uploadProgress.percent = Math.min(90, Math.floor(this.uploadProgress.percent + increment));
        } else {
          // 停留在90%，等待实际上传完成
          clearInterval(this.progressTimer);
        }
      }, 300); // 每300毫秒更新一次
    },

    // 完成进度
    completeProgress() {
      // 清除定时器
      if (this.progressTimer) {
        clearInterval(this.progressTimer);
        this.progressTimer = null;
      }

      // 设置为100%
      this.uploadProgress.percent = 100;

      // 延迟隐藏进度条
      setTimeout(() => {
        this.uploadProgress.visible = false;
      }, 800);
    },

    async handleSuccess(response, file) {
      // 创建专用于文件上传的axios实例，不设置超时限制
      const uploadInstance = axios.create({
        baseURL: window.$conf.commonConf.baseUrl,
        timeout: 0,  // 0表示无超时限制
        headers: {
          Authorization: 'Bearer ' + (localStorage.getItem("token") || Store.state.token)
        }
      });
      if (response.code === 0) {
        // 服务器返回的数据
        const fileData = response.data;

        this.fileInfo = {
          name: file.name,
          size: file.size,
          url: fileData.url || fileData.path
        }

        let contractInfo = null;
        try {
          // 从原始响应中获取文件对象或创建新的文件对象
          let fileObject = null;

          // 尝试从URL获取文件
          if (fileData.url) {
            try {
              const fileResponse = await fetch(fileData.url);
              const blob = await fileResponse.blob();
              fileObject = new File([blob], fileData.name || file.name, { type: file.type });
            } catch (error) {
              console.error('获取文件内容失败:', error);
            }
          }

          // 如果无法获取文件内容，使用原始文件
          if (!fileObject) {
            fileObject = file;
          }

          // 首先上传文件到 OSS
          const formData = new FormData();
          formData.append('upfile', fileObject);

          // 上传文件到 OSS
          const ossResponse = await uploadInstance.post('/system/oss/upload', formData);
          
          if (ossResponse.data.code === 0 && ossResponse.data.data.url) {
            // 使用 form-data 形式传参调用合同分析接口
            const analyzeFormData = new FormData();
            analyzeFormData.append('fileUrl', ossResponse.data.data.url);
            analyzeFormData.append('userId', parseInt(localStorage.getItem('userId') || '1111111111', 10));

            const uploadResponse = await uploadInstance.post('/api/files/analyzeContractInfo', analyzeFormData);

            // 完成进度条
            this.completeProgress();

            if (uploadResponse) {
              contractInfo = uploadResponse.data || {};
              console.log('文件信息处理结果:', contractInfo);
            } else {
              console.warn('文件信息处理警告:', uploadResponse);
              this.$message.warning('文件信息处理完成，但可能存在问题');
            }
          } else {
            console.warn('OSS上传警告:', ossResponse);
            this.$message.warning('OSS上传完成，但可能存在问题');
            this.completeProgress();
          }
        } catch (error) {
          console.error('调用文件上传接口出错:', error);
          this.$message.warning('文件已上传，但信息处理出现问题');
          this.completeProgress();
        }

        this.$router.push({
          path: '/home/contract/review',
          query: {
            // 文件基本信息
            fileId: fileData.id || fileData.fileName || fileData.path,
            fileName: fileData.name || fileData.originalFileName || file.name,
            fileUrl: fileData.url || fileData.path,
            fileSize: fileData.size || file.size,

            // 合同详细信息
            contractType: contractInfo.contractType,
            contractAmount: contractInfo.contractAmount,
            contractTerm: contractInfo.contractTerm,
            contentSummary: contractInfo.contentSummary,
            partyA: contractInfo.partyA,
            partyB: contractInfo.partyB
          }
        })
        this.$emit('upload-success', fileData)
      } else {
        this.completeProgress();
        this.$message.error(response.msg || '上传失败')
      }
    },
    handleError() {
      this.completeProgress();
      this.$message.error('上传失败，请重试')
    },
    removeFile() {
      this.fileInfo = null
      this.$emit('remove-file')
    },
    formatFileSize(size) {
      if (size < 1024) {
        return size + 'B'
      } else if (size < 1024 * 1024) {
        return (size / 1024).toFixed(2) + 'KB'
      } else {
        return (size / (1024 * 1024)).toFixed(2) + 'MB'
      }
    },
    formatDate(dateString) {
      if (!dateString) return '';

      try {
        const date = new Date(dateString);
        return date.toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit'
        });
      } catch (e) {
        console.error('日期格式化错误:', e);
        return dateString;
      }
    },
    async deleteHistoryItem(item) {
      try {
        // 弹出确认对话框
        this.$confirm(`确认删除合同 "${item.fileName}" 吗？删除后将无法恢复，包括所有关联的审核记录和规则数据。`, '删除确认', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          // 用户确认删除
          const response = await cascadeDeleteContract(item.id || item.contractId);
          if (response && response.code === 0) {
            this.$message.success('删除成功');
            this.getHistoryList();
          } else {
            this.$message.error(response.msg || '删除失败');
          }
        }).catch(() => {
          // 用户取消删除
          this.$message.info('已取消删除');
        });
      } catch (error) {
        console.error('删除历史记录出错:', error);
        this.$message.error('删除历史记录出错');
      }
    },
    getStatusClass(reviewStatus) {
      // 根据reviewStatus返回相应的类名
      switch (reviewStatus) {
        case 'completed':
          return 'status-completed';
        case 'reviewing':
          return 'status-reviewing';
        case 'pending':
          return 'status-pending';
        default:
          return 'status-pending';
      }
    },
    getStatusText(reviewStatus) {
      // 根据reviewStatus返回相应的文本
      switch (reviewStatus) {
        case 'completed':
          return '已完成';
        case 'reviewing':
          return '审核中';
        case 'pending':
          return '待审核';
        default:
          return '待审核';
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.contract-upload {
  max-width: 800px;
  margin: 0 auto;
  padding: 40px 20px;
  position: relative;

  .page-header {
    text-align: center;
    margin-bottom: 40px;

    .title {
      font-size: 28px;
      color: #303133;
      margin-bottom: 16px;
      font-weight: 500;
    }

    .subtitle {
      font-size: 16px;
      color: #909399;
      margin: 0;
    }
  }

  /* 历史记录按钮样式 */
  .history-button {
    position: absolute;
    top: 10px;
    left: 0;
    padding: 8px 15px;
    background-color: #f5f7fa;
    border-radius: 4px;
    cursor: pointer;
    display: flex;
    align-items: center;
    font-size: 14px;
    color: #606266;

    &:hover {
      background-color: #e6f1fc;
      color: #409EFF;
    }

    i {
      margin-right: 5px;
    }
  }

  .upload-container {
    background: #fff;
    border-radius: 8px;
    padding: 32px;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);

    .upload-area {
      width: 100%;
      border: 0px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;

      &:hover {
        border-color: #409EFF;
      }
    }

    .upload-content {
      width: 100%;
      text-align: center;

      .el-icon-upload {
        font-size: 48px;
        color: #909399;
        margin-bottom: 16px;
      }

      .upload-text {
        font-size: 16px;
        color: #606266;
        margin-bottom: 8px;
      }

      .upload-hint {
        font-size: 12px;
        color: #909399;
      }
    }

    .upload-info {
      margin-top: 16px;
      padding: 8px 16px;
      background: #f5f7fa;
      border-radius: 4px;
      display: flex;
      align-items: center;

      .file-name {
        flex: 1;
        margin-right: 16px;
        color: #606266;
      }

      .file-size {
        color: #909399;
        margin-right: 16px;
      }
    }

    .quota-info {
      margin-top: 16px;
      color: #909399;
      font-size: 12px;

      .el-icon-info {
        margin-right: 4px;
      }
    }
  }
  ::v-deep .el-upload-dragger {
    width: 700px;
  }

  .upload-progress-overlay {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(255, 255, 255, 0.9);
    z-index: 100;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .upload-progress-container {
    background-color: white;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    text-align: center;
    width: 80%;
    max-width: 400px;

    i {
      font-size: 42px;
      color: #3e7af9;
      margin-bottom: 15px;
    }

    .progress-text {
      font-size: 16px;
      color: #333;
      margin-bottom: 15px;
      font-weight: 500;
    }

    .el-progress {
      margin-top: 15px;
    }
  }

  /* 历史记录弹窗样式 */
  .history-dialog-content {
    .history-search {
      margin-bottom: 15px;
    }

    .history-tabs {
      margin-bottom: 10px;
    }

    .history-list {
      max-height: 350px;
      overflow-y: auto;

      .history-item {
        padding: 12px 16px;
        border-bottom: 1px solid #ebeef5;
        cursor: pointer;
        transition: background-color 0.3s;
        display: flex;
        justify-content: space-between;
        align-items: center;

        &:hover {
          background-color: #f5f7fa;
        }

        .history-item-content {
          flex: 1;
          cursor: pointer;
        }

        .history-item-name {
          font-size: 14px;
          color: #409EFF;
        }

        .history-item-info {
          display: flex;
          align-items: center;
          margin-top: 5px;
          font-size: 12px;
          color: #909399;

          .history-item-date {
            margin-right: 10px;
          }

          .history-item-status {
            padding: 2px 6px;
            border-radius: 2px;
            font-size: 12px;

            &.status-completed {
              color: #67c23a;
              background-color: #f0f9eb;
              border: 1px solid #e1f3d8;
            }

            &.status-reviewing {
              color: #e6a23c;
              background-color: #fdf6ec;
              border: 1px solid #faecd8;
            }

            &.status-pending {
              color: #909399;
              background-color: #f4f4f5;
              border: 1px solid #e9e9eb;
            }
          }
        }

        .history-item-actions {
          margin-left: 10px;
        }
      }

      .empty-history {
        text-align: center;
        padding: 30px 0;
        color: #909399;

        i {
          font-size: 40px;
          margin-bottom: 10px;
        }
      }
    }

    /* 分页器样式 */
    .pagination-container {
      margin-top: 15px;
      text-align: right;
    }
  }
}
</style>
